// 产品渠道映射配置接口
export interface ProductChannelConfig {
  channelCode: string | undefined  // 渠道代码，undefined表示未配置
  enabled: boolean                 // 是否启用该产品
  extraInfo?: {                    // 额外配置信息
    field1?: string               // 产品配置字段1
    field2?: number              // 产品配置字段2
    [key: string]: any            // 其他配置参数
  }
}

// 渠道商户配置接口
export interface ChannelMerchantConfig {
  channelCode: string              // 渠道代码
  connectMode: 'DIRECT' | 'INDIRECT' // 连接模式
  enabled: boolean                 // 是否启用该渠道
  configData: { [key: string]: any } // 配置数据 - 使用map对象，每个渠道格式不同，可包含分区信息
  status: 'ACTIVE' | 'INACTIVE' | 'PENDING' // 配置状态
  lastUpdateTime: string           // 最后更新时间
  description?: string             // 配置描述
}

// 支付应用配置 Mock数据 - 基于应用配置表结构
export interface AppConfig {
  appId: string           // 应用ID(格式: APP+13位时间戳)
  appName: string         // 应用名称
  appType: string         // 应用类型：CASHIER-收银台，MOBILE-移动支付，WEB-网页支付
  merchantId: string      // 所属商户ID
  connectMode: string     // 连接模式：DIRECT-直连，INDIRECT-间连
  appDescription?: string // 应用描述
  callbackUrl?: string    // 回调地址
  notifyUrl?: string      // 通知地址
  status: number          // 状态：0-禁用，1-启用
  createdTime: string     // 创建时间
  updatedTime: string     // 更新时间
  productChannelMapping: { [productCode: string]: ProductChannelConfig } // 产品-渠道映射
  channelMerchantConfigs?: { [channelCode: string]: ChannelMerchantConfig } // 渠道商户配置
}

export const appConfigs: AppConfig[] = [
  {
    appId: 'APP1735689600000',
    appName: '华东收银台',
    appType: 'CASHIER',
    merchantId: 'M1746866325792',
    connectMode: 'INDIRECT',
    appDescription: '华东收银测试商户的收银台应用',
    callbackUrl: 'https://merchant.example.com/callback',
    notifyUrl: 'https://merchant.example.com/notify',
    status: 1,
    createdTime: '2024-01-01 10:00:00',
    updatedTime: '2024-01-15 10:00:00',
    productChannelMapping: {
      'WXPAY_NATIVE': {
        channelCode: 'CHANNEL_IF_HUIFU',  // 汇付天下
        enabled: true,
        extraInfo: {
          field1: 'HF202401001',
          field2: 0.55
        }
      },
      'ALIPAY_NATIVE': {
        channelCode: 'CHANNEL_IF_HUIFU',  // 汇付天下
        enabled: true,
        extraInfo: {
          field1: 'HF202401001',
          field2: 0.52
        }
      },
      'WXPAY_JSAPI': {
        channelCode: 'CHANNEL_IF_FUIOU',  // 富友支付
        enabled: true,
        extraInfo: {
          field1: 'FY202401001',
          field2: 0.58
        }
      },
      'WXPAY_H5': {
        channelCode: 'CHANNEL_IF_LESHUA',  // 乐刷支付
        enabled: true,
        extraInfo: {
          field1: 'FY202401001',
          field2: 0.58
        }
      },
      'ALIPAY_H5': {
        channelCode: 'CHANNEL_IF_LESHUA',  // 乐刷支付
        enabled: true,
        extraInfo: {
          field1: 'ALI202401001',
          feeRate: 0.58
        }
      },
      'ALIPAY_JSAPI': {
        channelCode: undefined,  // 未配置
        enabled: false
      },
      'WXPAY_APP': {
        channelCode: undefined,  // 未配置
        enabled: false
      },
      'ALIPAY_APP': {
        channelCode: undefined,  // 未配置
        enabled: false
      }
    },
    channelMerchantConfigs: {
      'CHANNEL_IF_LESHUA': {
        channelCode: 'CHANNEL_IF_LESHUA',
        connectMode: 'INDIRECT',
        enabled: true,
        configData: {
          // 基础配置分区
          basic: {
            merchantNo: '7939611162',
            disableCreditCard: false,
            transactionFlag: 'D1'
          }
        },
        status: 'ACTIVE',
        lastUpdateTime: '2024-01-15 10:00:00',
        description: '华东收银测试商户的乐刷支付子商户配置'
      }
    }
  },
  {
    appId: 'APP1735689700000',
    appName: '惊喜来移动支付',
    appType: 'MOBILE',
    merchantId: 'M1746866425893',
    connectMode: 'INDIRECT',
    appDescription: '惊喜来干货店的移动支付应用',
    callbackUrl: 'https://jingxilai.example.com/callback',
    notifyUrl: 'https://jingxilai.example.com/notify',
    status: 1,
    createdTime: '2024-01-02 10:00:00',
    updatedTime: '2024-01-16 10:00:00',
    productChannelMapping: {
      'WXPAY_APP': {
        channelCode: 'CHANNEL_IF_LESHUA',  // 乐刷支付
        enabled: true,
        extraInfo: {
          field1: 'LS202401002',
          field2: 0.6
        }
      },
      'ALIPAY_APP': {
        channelCode: 'CHANNEL_IF_LESHUA',  // 乐刷支付
        enabled: true,
        extraInfo: {
          field1: 'LS202401002',
          field2: 0.58
        }
      },
      'WXPAY_NATIVE': {
        channelCode: undefined,  // 未配置
        enabled: false
      },
      'ALIPAY_NATIVE': {
        channelCode: undefined,  // 未配置
        enabled: false
      },
      'WXPAY_JSAPI': {
        channelCode: undefined,  // 未配置
        enabled: false
      },
      'ALIPAY_JSAPI': {
        channelCode: undefined,  // 未配置
        enabled: false
      }
    }
  },
  {
    appId: 'APP1735689800000',
    appName: '测试网页支付',
    appType: 'WEB',
    merchantId: 'M1746866325792',
    connectMode: 'DIRECT',
    appDescription: '测试用的网页支付应用',
    callbackUrl: 'https://test.example.com/callback',
    notifyUrl: 'https://test.example.com/notify',
    status: 0,
    createdTime: '2024-01-03 10:00:00',
    updatedTime: '2024-01-17 10:00:00',
    productChannelMapping: {
      'WXPAY_JSAPI': {
        channelCode: 'CHANNEL_IF_WXPAY',  // 微信支付直连
        enabled: true,
        extraInfo: {
          field1: 'WX1900000109',
          field2: 0.6
        }
      },
      'ALIPAY_JSAPI': {
        channelCode: 'CHANNEL_IF_ALIPAY',  // 支付宝直连
        enabled: true,
        extraInfo: {
          field1: 'ALI2088123456789012',
          field2: 0.55
        }
      },
      'WXPAY_H5': {
        channelCode: 'CHANNEL_IF_WXPAY',  // 微信支付直连
        enabled: false,       // 暂时禁用
        extraInfo: {
          field1: 'WX1900000109'
        }
      },
      'WXPAY_NATIVE': {
        channelCode: undefined,  // 未配置
        enabled: false
      },
      'ALIPAY_NATIVE': {
        channelCode: undefined,  // 未配置
        enabled: false
      },
      'WXPAY_APP': {
        channelCode: undefined,  // 未配置
        enabled: false
      },
      'ALIPAY_APP': {
        channelCode: undefined,  // 未配置
        enabled: false
      }
    }
  }
]

// 应用状态枚举
export const AppStatus = {
  DISABLED: 0,        // 禁用
  ENABLED: 1          // 启用
}

// 应用类型枚举
export const AppType = {
  CASHIER: 'CASHIER',    // 收银台
  MOBILE: 'MOBILE',      // 移动支付
  WEB: 'WEB'            // 网页支付
}

// 连接模式枚举
export const ConnectMode = {
  DIRECT: 'DIRECT',      // 直连
  INDIRECT: 'INDIRECT'   // 间连
}

// 获取应用状态名称
export const getAppStatusName = (status: number): string => {
  const statusMap: { [key: number]: string } = {
    0: '禁用',
    1: '启用'
  }
  return statusMap[status] || '未知'
}

// 获取应用状态颜色
export const getAppStatusColor = (status: number): string => {
  const colorMap: { [key: number]: string } = {
    0: 'default',
    1: 'success'
  }
  return colorMap[status] || 'default'
}

// 获取应用类型名称
export const getAppTypeName = (appType: string): string => {
  const typeMap: { [key: string]: string } = {
    'CASHIER': '收银台',
    'MOBILE': '移动支付',
    'WEB': '网页支付'
  }
  return typeMap[appType] || appType
}

// 获取应用类型颜色
export const getAppTypeColor = (appType: string): string => {
  const colorMap: { [key: string]: string } = {
    'CASHIER': 'blue',
    'MOBILE': 'green',
    'WEB': 'orange'
  }
  return colorMap[appType] || 'default'
}

// 获取连接模式名称
export const getConnectModeName = (connectMode: string): string => {
  const modeMap: { [key: string]: string } = {
    'DIRECT': '直连',
    'INDIRECT': '间连'
  }
  return modeMap[connectMode] || connectMode
}

// 获取连接模式颜色
export const getConnectModeColor = (connectMode: string): string => {
  const colorMap: { [key: string]: string } = {
    'DIRECT': 'blue',
    'INDIRECT': 'green'
  }
  return colorMap[connectMode] || 'default'
}

// 根据应用ID获取应用名称
export const getAppName = (appId: string): string => {
  const app = appConfigs.find(a => a.appId === appId)
  return app ? app.appName : appId
}

// 生成新的应用ID
export const generateAppId = (): string => {
  return 'APP' + Date.now().toString()
}

// 根据条件筛选应用配置
export const filterAppConfigs = (filters: {
  appName?: string
  appId?: string
  merchantId?: string
  appType?: string
  status?: number
}) => {
  return appConfigs.filter(app => {
    if (filters.appName && !app.appName.toLowerCase().includes(filters.appName.toLowerCase())) {
      return false
    }
    if (filters.appId && !app.appId.includes(filters.appId)) {
      return false
    }
    if (filters.merchantId && app.merchantId !== filters.merchantId) {
      return false
    }
    if (filters.appType && app.appType !== filters.appType) {
      return false
    }
    if (filters.status !== undefined && app.status !== filters.status) {
      return false
    }
    return true
  })
}

// 模拟API - 获取应用配置列表
export const mockLoadAppConfigs = (params: any): Promise<{
  data: AppConfig[];
  total: number;
}> => {
  const { current = 1, pageSize = 10, appName, appId, merchantId, appType, connectMode, status } = params

  let filteredData = appConfigs

  if (appName) {
    filteredData = filteredData.filter((app) => app.appName.includes(appName))
  }
  if (appId) {
    filteredData = filteredData.filter((app) => app.appId.includes(appId))
  }
  if (merchantId) {
    filteredData = filteredData.filter((app) => app.merchantId === merchantId)
  }
  if (appType) {
    filteredData = filteredData.filter((app) => app.appType === appType)
  }
  if (connectMode) {
    filteredData = filteredData.filter((app) => app.connectMode === connectMode)
  }
  if (status !== undefined && status !== null) {
    filteredData = filteredData.filter((app) => app.status === Number(status))
  }

  const total = filteredData.length
  const start = (current - 1) * pageSize
  const end = start + pageSize
  const paginatedData = filteredData.slice(start, end)

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        data: paginatedData,
        total: total
      })
    }, 1000)
  })
}

// 模拟API - 保存应用配置
export const mockSaveAppConfig = (appConfig: AppConfig): Promise<{
  success: boolean;
  message: string;
}> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        success: true,
        message: '保存成功'
      })
    }, 500)
  })
}

// 模拟API - 删除应用配置
export const mockDeleteAppConfig = (appId: string): Promise<{
  success: boolean;
  message: string;
}> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        success: true,
        message: '删除成功'
      })
    }, 500)
  })
}


// 模拟API - 获取产品配置
export const mockLoadProductConfig = (appId: string): Promise<{
  data: any[];
}> => {
  return new Promise((resolve) => {
    setTimeout(async () => {
      // 查找应用配置
      const app = appConfigs.find(a => a.appId === appId);
      if (!app) {
        resolve({ data: [] });
        return;
      }

      try {
        // 动态导入products.ts和channels.ts中的数据
        const { paymentProducts } = await import('./products');
        const { paymentChannels } = await import('./channels');

        const products: any[] = Object.entries(app.productChannelMapping).map(([productCode, config]) => {
          // 从products.ts中找到对应的产品
          const baseProduct = paymentProducts.find(p => p.productCode === productCode);
          if (!baseProduct) return null;

          // 从channels.ts中获取渠道信息（如果已配置）
          const channel = config.channelCode ? paymentChannels.find(c => c.channelCode === config.channelCode) : null;

          return {
            productCode: baseProduct.productCode,
            productName: baseProduct.productName,
            productType: baseProduct.productType,
            enabled: config.enabled,
            feeRate: config.extraInfo?.field2 || (channel ? 0.6 : 0), // 默认费率
            minAmount: baseProduct.minAmount,
            maxAmount: baseProduct.maxAmount,
            channelMappings: channel ? [{
              channelCode: channel.channelCode,
              channelName: channel.channelName,
              merchantNo: config.extraInfo?.field1 || '',
              feeRate: config.extraInfo?.field2 || 0.6,
              enabled: config.enabled,
              channelType: channel.supportDirect ? 'DIRECT' : 'INDIRECT',
              configStatus: config.enabled ? 'ACTIVE' : 'INACTIVE'
            }] : [],
            description: baseProduct.productDesc,
            supportedScenes: [baseProduct.productType]
          };
        }).filter(Boolean);

        resolve({ data: products });
      } catch (error) {
        console.error('Error loading product config:', error);
        resolve({ data: [] });
      }
    }, 500)
  })
}

// 渠道配置接口定义
export interface ChannelConfig {
  channelId: string;
  channelName: string;
  channelCode: string;
  channelType: 'DIRECT' | 'INDIRECT';
  merchantNo: string;
  enabled: boolean;
  feeRate: number;
  configStatus: 'ACTIVE' | 'INACTIVE' | 'PENDING';
  supportedProducts: string[];
  configDetails: {
    appId?: string;
    appSecret?: string;
    merchantId?: string;
    publicKey?: string;
    privateKey?: string;
    notifyUrl?: string;
    returnUrl?: string;
    [key: string]: any;
  };
  lastUpdateTime: string;
  description?: string;
}


// 模拟API - 获取渠道配置
export const mockLoadChannelConfig = (appId: string): Promise<{
  data: ChannelConfig[];
}> => {
  return new Promise((resolve) => {
    setTimeout(async () => {
      // 查找应用配置
      const app = appConfigs.find(a => a.appId === appId);
      if (!app) {
        resolve({ data: [] });
        return;
      }

      try {
        // 动态导入channels.ts中的数据
        const { paymentChannels } = await import('./channels');

        // 获取应用中使用的所有渠道
        const usedChannelCodes = new Set<string>();
        Object.values(app.productChannelMapping).forEach(config => {
          if (config.channelCode) {
            usedChannelCodes.add(config.channelCode);
          }
        });

        const channels: ChannelConfig[] = Array.from(usedChannelCodes).map(channelCode => {
          // 从channels.ts中找到对应的渠道
          const baseChannel = paymentChannels.find(c => c.channelCode === channelCode);
          if (!baseChannel) return null;

          // 获取该渠道的配置信息（从第一个使用该渠道的产品配置中获取）
          const productConfig = Object.values(app.productChannelMapping).find(config => config.channelCode === channelCode);

          return {
            channelId: baseChannel.channelId,
            channelName: baseChannel.channelName,
            channelCode: baseChannel.channelCode,
            channelType: baseChannel.supportDirect ? 'DIRECT' : 'INDIRECT',
            merchantNo: productConfig?.extraInfo?.field1 || '',
            enabled: productConfig?.enabled || false,
            feeRate: productConfig?.extraInfo?.field2 || 0.6,
            configStatus: 'ACTIVE' as const,
            supportedProducts: baseChannel.supportedProducts,
            configDetails: productConfig?.extraInfo || {},
            lastUpdateTime: new Date().toLocaleString(),
            description: `${baseChannel.channelName} - ${baseChannel.settlementCycle}结算`
          };
        }).filter(Boolean) as ChannelConfig[];

        resolve({ data: channels });
      } catch (error) {
        console.error('Error loading channel config:', error);
        resolve({ data: [] });
      }
    }, 500)
  })
}

// 模拟API - 获取设备列表
export const mockLoadDeviceList = (appId: string): Promise<{
  data: Array<{
    deviceId: string;
    deviceName: string;
    location: string;
    status: string;
  }>;
}> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        data: [
          {
            deviceId: 'DEV001',
            deviceName: '收银台001',
            location: '华东收银测试店',
            status: 'ACTIVE'
          },
          {
            deviceId: 'DEV002',
            deviceName: '收银台002',
            location: '惊喜来干货店',
            status: 'ACTIVE'
          }
        ]
      })
    }, 500)
  })
}

// 模拟API - 获取商户相关数据
export const mockLoadMerchantRelatedData = (merchantId: string): Promise<{
  provider: {
    providerId: string;
    providerName: string;
  };
  channels: any[];
}> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        provider: {
          providerId: 'SP1752154718336',
          providerName: '火金科技'
        },
        channels: []
      })
    }, 500)
  })
}

// 模拟API - 获取应用渠道商户配置
export const mockLoadAppChannelMerchantConfigs = (appId: string): Promise<{
  data: ChannelMerchantConfig[];
}> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const app = appConfigs.find(a => a.appId === appId)
      if (!app || !app.channelMerchantConfigs) {
        resolve({ data: [] })
        return
      }

      const configs = Object.values(app.channelMerchantConfigs)
      resolve({ data: configs })
    }, 500)
  })
}

// 模拟API - 获取特定渠道的商户配置
export const mockLoadChannelMerchantConfig = (appId: string, channelCode: string): Promise<{
  data: ChannelMerchantConfig | null;
}> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const app = appConfigs.find(a => a.appId === appId)
      if (!app || !app.channelMerchantConfigs) {
        resolve({ data: null })
        return
      }

      const config = app.channelMerchantConfigs[channelCode] || null
      resolve({ data: config })
    }, 500)
  })
}

// 模拟API - 保存渠道商户配置
export const mockSaveChannelMerchantConfig = (appId: string, config: ChannelMerchantConfig): Promise<{
  success: boolean;
  message: string;
}> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const app = appConfigs.find(a => a.appId === appId)
      if (!app) {
        resolve({ success: false, message: '应用不存在' })
        return
      }

      // 初始化 channelMerchantConfigs 如果不存在
      if (!app.channelMerchantConfigs) {
        app.channelMerchantConfigs = {}
      }

      // 更新配置
      app.channelMerchantConfigs[config.channelCode] = {
        ...config,
        lastUpdateTime: new Date().toLocaleString()
      }

      resolve({ success: true, message: '保存成功' })
    }, 500)
  })
}

// 辅助函数 - 根据应用ID获取渠道商户配置
export const getAppChannelMerchantConfigs = (appId: string): ChannelMerchantConfig[] => {
  const app = appConfigs.find(a => a.appId === appId)
  if (!app || !app.channelMerchantConfigs) {
    return []
  }
  return Object.values(app.channelMerchantConfigs)
}

// 辅助函数 - 根据应用ID和渠道代码获取商户配置
export const getChannelMerchantConfig = (appId: string, channelCode: string): ChannelMerchantConfig | null => {
  const app = appConfigs.find(a => a.appId === appId)
  if (!app || !app.channelMerchantConfigs) {
    return null
  }
  return app.channelMerchantConfigs[channelCode] || null
}